import os
import subprocess
import ffmpeg

AD_DIR_NAME="AD"

def get_video_info(path):
    """获取视频时长和分辨率"""
    try:
        probe = ffmpeg.probe(path)
        width = int(probe['streams'][0]['width'])
        height = int(probe['streams'][0]['height'])
        duration = float(probe['format']['duration'])
        return duration, width, height
    except Exception as e:
        print(f"获取视频信息失败: {path}, 错误: {e}")
        return 5, 1920, 1080  # 默认值

def _calculate_scale(main_w, main_h, overlay_type):
    """计算overlay缩放比例"""
    # 横屏以宽度占主视频 30% 为准，竖屏以高度占主视频 20% 为准
    if main_w >= main_h:
        scale_w = int(main_w * 0.3 * 2)
        scale_h = -1
    else:
        scale_w = -1
        if overlay_type == "football":
            scale_h = int(main_h * 0.2 * 1.25)
        else:  # game
            scale_h = int(main_h * 0.2)
    
    return scale_w, scale_h

def _build_ffmpeg_cmd(input_path, overlay_mov, output_path, 
                      start_time=None,
                      position_type="middle"):
    """构建ffmpeg命令"""
    overlay_dur, overlay_w, overlay_h = get_video_info(overlay_mov)
    main_dur, main_w, main_h = get_video_info(input_path)
    if start_time is None:
        start_time = main_dur / 2 # 原来的代码，从中间开始播放
    else:
        start_time = start_time
    
    # 计算 overlay 缩放比例
    overlay_type = "football" if "足球" in overlay_mov else "game"
    scale_w, scale_h = _calculate_scale(main_w, main_h, overlay_type)
    scale_filter = f"scale={scale_w}:{scale_h}"
    
    if position_type == "top":
        # 足球广告置顶
        cmd = [
            "ffmpeg",
            "-i", input_path,
            "-i", overlay_mov,
            "-filter_complex",
            (
                f"[1:v]trim=0:{overlay_dur},"
                f"setpts=PTS-STARTPTS+{start_time}/TB,"  # 时间戳平移到主视频 start_time
                f"{scale_filter}[ov];"
                f"[0:v][ov]overlay=x=(W-w)/2:y=0:"       # 置顶
                f"enable='between(t,{start_time},{start_time + overlay_dur})'"
            ),
            "-c:a", "copy",  # 保留主视频音频
            "-y",
            output_path
        ]
    else:  # middle
        # 游戏广告居中偏上
        cmd = [
            "ffmpeg",
            "-i", input_path,
            "-i", overlay_mov,
            "-filter_complex",
            (
                f"[1:v]trim=0:{overlay_dur},"
                f"fade=t=in:st=0:d=1,"
                f"fade=t=out:st={overlay_dur-1}:d=1,"
                f"setpts=PTS-STARTPTS+{start_time}/TB,"
                f"{scale_filter}[ov];"
                f"[0:v][ov]overlay=(W-w)/2:(H-h)/3:"
                f"enable='between(t,{start_time-2},{start_time + overlay_dur + 2})'"
            ),
            "-c:a", "copy",
            "-y",
            output_path
        ]
    
    return cmd, overlay_dur, overlay_w, overlay_h

def embed_ad_dir(input_dir, overlay_mov, start_time=None,position_type="middle"):
    """为目录中的所有视频添加广告"""
    output_dir = os.path.join(input_dir, AD_DIR_NAME)
    os.makedirs(output_dir, exist_ok=True)
    
    for filename in os.listdir(input_dir):
        if not filename.lower().endswith(('.mp4', '.mov', '.mkv', '.avi')):
            continue

        input_path = os.path.join(input_dir, filename)
        output_path = os.path.join(output_dir, filename)
        
        cmd, overlay_dur, overlay_w, overlay_h = _build_ffmpeg_cmd(
            input_path, overlay_mov, output_path, start_time, position_type)
        
        print(f"overlay时长: {overlay_dur:.2f}s, 分辨率: {overlay_w}x{overlay_h}")
        print(f"处理: {filename}")
        subprocess.run(cmd, check=True)

    print("全部处理完成！")

def embed_ad_single(input_path, overlay_mov, start_time=None ,position_type="middle"):
    """为单个视频添加广告"""
    # 获取目录和文件名
    dir_name = os.path.dirname(input_path)
    base_name = os.path.basename(input_path)

    # 创建 AD 子文件夹路径
    ad_dir = os.path.join(dir_name, AD_DIR_NAME)
    os.makedirs(ad_dir, exist_ok=True)  # 如果不存在则创建

    # 生成输出文件路径（放在 AD 文件夹中）
    output_path = os.path.join(ad_dir, base_name)
    
    cmd, overlay_dur, overlay_w, overlay_h = _build_ffmpeg_cmd(
        input_path, overlay_mov, output_path, start_time, position_type)
    
    print(f"overlay时长: {overlay_dur:.2f}s, 分辨率: {overlay_w}x{overlay_h}")
    print(f"处理: {input_path}")
    subprocess.run(cmd, check=True)

def embed_game_ad_dir(input_dir):
    """为目录中的所有视频添加游戏广告（保持向后兼容）"""
    overlay_mov = r"\\Fw-152\e\媒体部素材\广告\电子竞技弹窗.mov"
    return embed_ad_dir(input_dir, overlay_mov, None,"middle")

def embed_football_ad_dir(input_dir):
    """为目录中的所有视频添加足球广告（保持向后兼容）"""
    overlay_mov = r"\\Fw-152\e\媒体部素材\广告\足球弹窗.mov"
    return embed_ad_dir(input_dir, overlay_mov, 2,"top")

def embed_football_ad_single(input_path):
    """为单个视频添加足球广告（保持向后兼容）"""
    overlay_mov = r"\\Fw-152\e\媒体部素材\广告\足球弹窗.mov"
    return embed_ad_single(input_path, overlay_mov, 2, "top")

def embed_game_ad_single(input_path):
    """为单个视频添加游戏广告（保持向后兼容）"""
    overlay_mov = r"\\Fw-152\e\媒体部素材\广告\电子竞技弹窗.mov"
    return embed_ad_single(input_path, overlay_mov, None, "middle")


if __name__ == "__main__":
    input_dir = r"\\Fw-152\e\媒体部素材\搬运测试\20251027\搬运\足球 赛事\团队配合费尔明扳平比分！.mp4"
    embed_football_ad_single(input_dir)